package fun.boomcat.luckyhe.mirai.plugin.command.utils;

import fun.boomcat.luckyhe.mirai.plugin.bean.ReplyType;
import net.mamoe.mirai.message.data.PlainText;
import net.mamoe.mirai.message.data.SingleMessage;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PrimitiveIterator;
import java.util.regex.Pattern;

public class ReplyCommandArgsHandler {
    public static Map<String, Object> getArgsMap(Object[] args) throws Exception {
//        reply add与reply del使用，传入原指令参数，返回map（包括type, keyword, reply）
        int i = 0;
        ReplyType rtype = null;
        String keyword = null;
        String reply = null;

//        flag
        int[] flag = {0, 0, 0};
        while (i < 6) {
            SingleMessage argName = (SingleMessage) args[i];

            if (!(argName instanceof PlainText)) {
                throw new IllegalArgumentException("有奇怪的参数" + argName.getClass());
            }

            String arg = args[i + 1].toString();

            switch (argName.toString().toLowerCase()) {
                case "-t":
                case "--type":
                    rtype = ReplyMapHandler.getReplyType(arg);
                    flag[0] = 1;
                    break;
                case "-k":
                case "--keyword":
                    keyword = ReplySentenceHandler.convertToOrigin(arg);
                    flag[1] = 1;
                    break;
                case "-r":
                case "--reply":
                    reply = ReplySentenceHandler.convertToOrigin(arg);
                    flag[2] = 1;
                    break;
                default:
                    throw new IllegalArgumentException("有奇怪的参数" + argName);
            }

            i += 2;
        }

//        check
        PrimitiveIterator.OfInt flagIterator = Arrays.stream(flag).iterator();
        while (flagIterator.hasNext()) {
            if (flagIterator.next() == 0) {
                throw new IllegalArgumentException("缺少参数");
            }
        }

        if (rtype == ReplyType.REGEX || rtype == ReplyType.REGEX_REPLACE) {
                String regex = keyword;
                Pattern.compile(regex);
        }

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("type", rtype);
        resMap.put("keyword", keyword);
        resMap.put("reply", reply);

        return resMap;
    }
}
